package oa.hleast.xswl.controller.admin.pms;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import oa.hleast.common.constant.ConfigKeyConstant;
import oa.hleast.common.enums.QueryModeEnum;
import oa.hleast.common.result.Result;
import oa.hleast.common.web.exception.BizException;
import oa.hleast.common.web.util.RequestUtils;
import oa.hleast.xswl.pojo.domain.SysCommonConfig;
import oa.hleast.xswl.pojo.domain.pms.PmsCategory;
import oa.hleast.xswl.pojo.vo.pms.CategoryVO;
import oa.hleast.xswl.service.ISysCommonConfigService;
import oa.hleast.xswl.service.pms.IPmsCategoryAttrService;
import oa.hleast.xswl.service.pms.IPmsCategoryService;
import oa.hleast.xswl.service.pms.IPmsCategorySpecService;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

@Api(tags = "【系统管理】商品分类")
@RestController
@RequestMapping("/api.admin/v1/categories")
@Slf4j
@AllArgsConstructor
public class CategoryController {

    private IPmsCategoryService iPmsCategoryService;

    private IPmsCategoryAttrService iPmsCategoryAttrService;

    private IPmsCategorySpecService iPmsCategorySpecService;

    private ISysCommonConfigService commonConfigService;

    @ApiOperation(value = "列表分页", httpMethod = "GET")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "queryMode", paramType = "query", dataType = "String", dataTypeClass = String.class),
    })
    @GetMapping
    public Result list(String queryMode) {
        QueryModeEnum queryModeEnum = QueryModeEnum.getValue(queryMode);
        PmsCategory category = new PmsCategory();
        List list;
        switch (queryModeEnum) {
            default:
                list = iPmsCategoryService.listForTree(null, category);
                return Result.success(list);
        }
    }

    @ApiOperation(value = "默认sku的商品分类列表", httpMethod = "GET")
    @GetMapping("/listByDefaultSku")
    public Result listByDefaultSku(String queryMode) {
        QueryModeEnum queryModeEnum = QueryModeEnum.getValue(queryMode);
        PmsCategory category = new PmsCategory();
        Long userId = RequestUtils.getUserId();
        SysCommonConfig commonConfig = commonConfigService.getByConfigKey(ConfigKeyConstant.SKU_DEFAULT_CATEGORY);
        Long categoryId = new Long(commonConfig.getValue());
        category.setParentId(categoryId);
        List list;
        switch (queryModeEnum) {
            case CASCADER:
                list = iPmsCategoryService.listForCascader(category);
                return Result.success(list);
            default:
                list = iPmsCategoryService.listForTree(userId, category);
                return Result.success(list);
        }
    }

    @ApiOperation(value = "商品分类详情", httpMethod = "GET")
    @ApiImplicitParam(name = "id", value = "商品分类id", required = true, paramType = "path", dataType = "Long", dataTypeClass = Long.class)
    @GetMapping("/{id}")
    public Result detail(@PathVariable Integer id) {
        PmsCategory category = iPmsCategoryService.getById(id);
        return Result.success(category);
    }

    @ApiOperation(value = "新增商品分类", httpMethod = "POST")
    @ApiImplicitParam(name = "category", value = "实体JSON对象", required = true, paramType = "body", dataType = "PmsCategory", dataTypeClass = PmsCategory.class)
    @PostMapping
    public Result add(@RequestBody PmsCategory category) {
        Long userId = RequestUtils.getUserId();
        category.setUserId(userId);
        iPmsCategoryService.save(category);
        CategoryVO categoryVO = new CategoryVO();
        BeanUtil.copyProperties(category, categoryVO);
        return Result.success(categoryVO);
    }

    @ApiOperation(value = "修改商品分类", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "商品分类id", required = true, paramType = "path", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "category", value = "实体JSON对象", required = true, paramType = "body", dataType = "PmsCategory", dataTypeClass = PmsCategory.class)
    })
    @PostMapping(value = "/put/{id}")
    public Result update(
            @PathVariable Integer id,
            @RequestBody PmsCategory category) {
        Long userId = RequestUtils.getUserId();
        PmsCategory pmsCategory = iPmsCategoryService.getById(category.getId());
        if (ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(pmsCategory.getUserId())) {
            throw new BizException("用户登录异常");
        }
        if (!pmsCategory.getUserId().equals(userId)) {
            throw new BizException("您只能修改自己的商品分类");
        }
        iPmsCategoryService.updateById(category);
        return Result.success(category);
    }

    @ApiOperation(value = "删除商品分类", httpMethod = "POST")
    @ApiImplicitParam(name = "ids", value = "id集合,以英文逗号','分隔", required = true, paramType = "query", dataType = "String", dataTypeClass = String.class)
    @PostMapping("/delete")
    public Result delete(@RequestParam String ids) {
        List<String> idList = Arrays.asList(ids.split(","));

        Optional.ofNullable(idList).ifPresent(list -> {

            list.forEach(id -> {
                iPmsCategoryAttrService.removeById(id);
                iPmsCategorySpecService.removeById(id);
            });

            iPmsCategoryService.removeByIds(idList.stream().map(id -> Long.parseLong(id)).collect(Collectors.toList()));
        });
        return Result.success();
    }

    @ApiOperation(value = "修改商品分类", httpMethod = "POST")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "用户id", required = true, paramType = "path", dataType = "Long", dataTypeClass = Long.class),
            @ApiImplicitParam(name = "category", value = "实体JSON对象", required = true, paramType = "body", dataType = "PmsCategory", dataTypeClass = PmsCategory.class)
    })
    @PostMapping(value = "/patch/{id}")
    public Result patch(@PathVariable Integer id, @RequestBody PmsCategory category) {
        LambdaUpdateWrapper<PmsCategory> updateWrapper = new LambdaUpdateWrapper<PmsCategory>().eq(PmsCategory::getId, id);
        updateWrapper.set(category.getStatus() != null, PmsCategory::getStatus, category.getStatus());
        boolean update = iPmsCategoryService.update(updateWrapper);
        return Result.success(update);
    }
}
